#include "imagesender.h"
#include <QDebug>
void ImageSender::sendImage(const QImage &image, const QString &address, quint16 port)
{
    QByteArray byteArray;
    QBuffer buffer(&byteArray);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG"); // 使用 PNG 格式以保留透明度

    const int totalBytes = byteArray.size();
    const int chunkSize = 1400;
    int bytesSent = 0;

    // 添加帧头
    QByteArray header;
    header.append(0xAA);
    header.append(0x55);

    // 发送图像总大小（4 个字节）
    QByteArray sizeArray;
    QDataStream sizeStream(&sizeArray, QIODevice::WriteOnly);
    sizeStream << totalBytes;
    qDebug()<<"发送图像大小:"<<totalBytes;
    // 组合帧头和总大小
    QByteArray packet = header + sizeArray;

    // 发送帧头
    udpSocket->writeDatagram(packet, QHostAddress(address), port);

    // 分块发送图像数据
    while (bytesSent < totalBytes)
    {
        qDebug()<<"发送图像:"<<bytesSent;
        QByteArray chunk = byteArray.mid(bytesSent, chunkSize);
        udpSocket->writeDatagram(chunk, QHostAddress(address), port);
        bytesSent += chunk.size();
    }
}
